const React = require('react');
const Index = require('./components/Index').default;
const { renderToString, renderToStaticMarkup } = require('react-dom/server');
/**
 Render a React element to its initial HTML. React will return an HTML string.
 You can use this method to generate HTML on the server and send the markup down on the initial request for faster page loads and to allow search engines to crawl your pages for SEO purposes.

 If you call ReactDOM.hydrate() on a node that already has this server-rendered markup, React will preserve it and only attach event handlers, allowing you to have a very performant first-load experience.
*/

const http = require('http');

//TODO 也可以把上面和component中的require改为import这样的es6语法,因为现在使用了webpack进行打包

//服务
http.createServer((req, res) => {
    res.writeHead(200, {
      'Content-Type': 'text/html'
    });

    // const html = renderToString(<Index/>);
    // ↕ 如果只是单纯的html渲染 此时上下是等价的
    const html = renderToStaticMarkup(<Index/>);

    res.end(`<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>React SSR</title>
</head>
<body>
    <div id="root">
       ${html}
    </div>
</body>
</html>`);
  }
).listen(9001);

console.log('server start. 9001');
